package main

import (
	"flag"
	"fmt"
	"google.golang.org/grpc/status"
	{{.importPackages}}
)

var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	ctx := svc.NewServiceContext(c)
	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	handler.RegisterHandlers(server, ctx)
	httpx.SetErrorHandler(func(err error) (int, interface{}) {
		if s, ok := status.FromError(err); ok {
			return http.StatusOK,&errorx.CodeErrorResponse{
				Code: strconv.Itoa(int(s.Code())),
				Msg: s.Message(),
			}
		}
		switch e:=err.(type) {
		case *errorx.CodeError:
			return http.StatusOK,e.Data()
		default:
			return http.StatusInternalServerError,e
		}
	})
	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
